#!/bin/sh
PYTHON_BIN="/var/packages/python38/target/bin/python3"
PACKAGE_BASE="/var/packages/nastool/target"
CONFIG_FILE="/var/packages/nastool/target/config/config.yaml"
TIMEOUT=30

running_nastool() {
    PIDS=$(/bin/ps -ef | sed -e 's/^[ \t]*//' | grep -v grep | grep run.py | awk '{print $2}')
    for PID in ${PIDS}
	do
	  return 0
	done
	return 1
}

start() {  
	if ! running_nastool ; then
	    export NASTOOL_CONFIG=${CONFIG_FILE}
		 "${PYTHON_BIN}" "${PACKAGE_BASE}/run.py" &
	fi

    i=0
    while true; do
        if ! running_nastool ; then
#           echo "WAIT: ${i}s of ${TIMEOUT}s"
            sleep 2s
            i=$((i+5))
        else
            break
        fi
        [ $i -ge ${TIMEOUT} ] && break
    done

    # 检查进程状态
    if ! running_nastool ; then
        echo "nastool进程已死"
        stop
        return 1
    fi

    return 0
}

# shellcheck disable=SC2120
stop() {
    # 检查进程状态
    if running_nastool ; then
      PIDS=$(/bin/ps -ef | sed -e 's/^[ \t]*//' | grep -v grep | grep run.py | awk '{print $2}' | cut -f1 -d' ')
      [ -z "${PIDS}" ] && return 0
      for PID in ${PIDS}
      do
        echo "Try to Kill the $1 process [ ${PID} ]"
        kill -15 "${PID}"
      done
      echo "Wait 3s..."
      sleep 3s
      if running_nastool ; then
        for PID in ${PIDS}
        do
          echo "Kill the $1 process [ ${PID} ]"
          kill -9 "${PID}"
        done
        sleep 2s
      fi
    fi

    return 0
}

case $1 in
    start)
        # 启动服务器
        start
        exit $?
    ;;
    stop)
        # 关闭服务器
        stop
        exit $?
    ;;
    status)
        exit 0
    ;;
    log)
        exit 1
    ;;
    *)
        exit 1
    ;;
esac
